<template>
  <view class="abnormal-parking-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="异常泊位管理" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 工单状态筛选 -->
            <view class="filter-item">
              <text class="filter-label">工单状态：</text>
              <up-tabs :list="statusList" :scrollable="false" @change="handleStatusChange" :current="currentStatus"></up-tabs>
            </view>
            
            <!-- 泊位号搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.berthNumber" :clearabled="true" :showAction="true" 
                placeholder="请输入泊位号" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="abnormal-parking-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              泊位号：<text class="number">{{ item.berthNumber }}</text>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">停车场：</text>
                <text class="value">{{ item.parkingLot }}</text>
              </view>
              <view class="item">
                <text class="label">异常原因：</text>
                <text class="value exception-type" :class="getExceptionTypeClass(item.exceptionType)">{{ item.exceptionType }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="处理" class="custom-style" 
                  @click="handleProcess(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 处理弹窗 -->
    <up-popup v-model:show="showProcessModal" mode="center" :round="10">
      <view class="process-modal">
        <view class="modal-header">
          <text class="modal-title">处理异常泊位</text>
          <up-icon name="close" @click="closeProcessModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">处理状态：</text>
            <up-radio-group v-model="processForm.processStatus">
              <up-radio name="pending" label="待处理"></up-radio>
              <up-radio name="completed" label="已处理"></up-radio>
              <up-radio name="rejected" label="驳回"></up-radio>
            </up-radio-group>
          </view>
          <view class="form-item">
            <text class="form-label">泊位状态：</text>
            <up-radio-group v-model="processForm.berthStatus">
              <up-radio name="enabled" label="启用"></up-radio>
              <up-radio name="disabled" label="禁用"></up-radio>
            </up-radio-group>
          </view>
          <view class="form-item">
            <text class="form-label">图片：</text>
            <view class="image-upload">
              <view class="image-list">
                <view class="image-item" v-for="(image, index) in processForm.images" :key="index">
                  <image :src="image" mode="aspectFill" class="uploaded-image"></image>
                  <up-icon name="close-circle-fill" class="delete-icon" @click="removeImage(index)"></up-icon>
                </view>
                <view class="upload-btn" @click="chooseImage" v-if="processForm.images.length < 3">
                  <up-icon name="plus" size="40"></up-icon>
                  <text class="upload-text">上传图片</text>
                </view>
              </view>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">备注：</text>
            <up-textarea v-model="processForm.remark" placeholder="请输入处理备注" maxlength="200"></up-textarea>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeProcessModal">取消</up-button>
          <up-button type="primary" @click="confirmProcess">确认处理</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 查看详情弹窗 -->
    <up-popup v-model:show="showDetailModal" mode="center" :round="10">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">工单详情</text>
          <up-icon name="close" @click="closeDetailModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="detail-item">
            <text class="detail-label">工单编号：</text>
            <text class="detail-value">{{ currentDetail.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">泊位编号：</text>
            <text class="detail-value">{{ currentDetail.berthNumber }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备编号：</text>
            <text class="detail-value">{{ currentDetail.deviceSN }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">工单类型：</text>
            <text class="detail-value">运维工单</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">异常类型：</text>
            <text class="detail-value">{{ currentDetail.exceptionType }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">创建时间：</text>
            <text class="detail-value">{{ currentDetail.createTime }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">负责人：</text>
            <text class="detail-value">{{ currentDetail.assigneeName || '未指派' }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="primary" @click="closeDetailModal">关闭</up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';

// 工单状态选项
const statusList = [
  { name: '全部' },
  { name: '待处理' },
  { name: '已处理' },
];
const currentStatus = ref(0);

// 搜索表单数据
const searchForm = reactive({
  berthNumber: '',
});

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 处理相关
const showProcessModal = ref(false);
const processForm = reactive({
  processStatus: 'pending',
  berthStatus: 'enabled',
  images: [],
  remark: ''
});
const currentProcessItem = ref(null);

// 查看详情相关
const showDetailModal = ref(false);
const currentDetail = ref({});

// 工单状态切换事件
const handleStatusChange = (e) => {
  currentStatus.value = e.index;
  if (paging.value) {
    paging.value.reload();
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchForm.berthNumber = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.navigateBack();
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'pending':
    case '待处理':
      return 'status-pending';
    case 'processing':
    case '处理中':
      return 'status-processing';
    case 'completed':
    case '已处理':
      return 'status-completed';
    default:
      return 'status-default';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待处理';
    case 'processing':
      return '处理中';
    case 'completed':
      return '已处理';
    default:
      return status || '未知状态';
  }
};

// 获取异常类型样式类
const getExceptionTypeClass = (type) => {
  switch (type) {
    case '设备故障':
      return 'exception-device';
    case '传感器异常':
      return 'exception-sensor';
    case '网络故障':
      return 'exception-network';
    case '电源故障':
      return 'exception-power';
    case '通信异常':
      return 'exception-communication';
    default:
      return 'exception-default';
  }
};

// 处理异常泊位
const handleProcess = (item) => {
  currentProcessItem.value = item;
  showProcessModal.value = true;
  // 重置表单
  processForm.processStatus = 'pending';
  processForm.berthStatus = 'enabled';
  processForm.images = [];
  processForm.remark = '';
};

// 确认处理
const confirmProcess = () => {
  // 这里应该调用API进行处理
  console.log('处理异常泊位:', {
    item: currentProcessItem.value,
    processStatus: processForm.processStatus,
    berthStatus: processForm.berthStatus,
    images: processForm.images,
    remark: processForm.remark
  });
  
  uni.showToast({
    title: '处理成功',
    icon: 'success'
  });
  
  closeProcessModal();
  
  // 刷新列表
  if (paging.value) {
    paging.value.reload();
  }
};

// 关闭处理弹窗
const closeProcessModal = () => {
  showProcessModal.value = false;
  currentProcessItem.value = null;
  processForm.processStatus = 'pending';
  processForm.berthStatus = 'enabled';
  processForm.images = [];
  processForm.remark = '';
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - processForm.images.length,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      processForm.images.push(...res.tempFilePaths);
    }
  });
};

// 删除图片
const removeImage = (index) => {
  processForm.images.splice(index, 1);
};

// 查看详情
const handleViewDetail = (item) => {
  currentDetail.value = item;
  showDetailModal.value = true;
};

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false;
};

// 获取运维工单列表数据
const queryList = async (pageNo, pageSize) => {
  const params = {
    pageNum: pageNo,
    pageSize,
    status: currentStatus.value,
    berthNumber: searchForm.berthNumber
  };

  await fetchList(params);
};

const fetchList = async (params) => {
  try {
    // 模拟API调用，实际项目中应该调用真实的API
    const mockData = generateMockData(params);
    
    paging.value.complete(mockData.records || []);
  } catch (error) {
    paging.value.complete(false);
  }
};

// 生成模拟数据
const generateMockData = (params) => {
  const records = [];
  const statuses = ['pending', 'processing', 'completed'];
  const exceptionTypes = ['设备故障', '传感器异常', '网络故障', '电源故障', '通信异常'];
  const parkingLots = ['停车场A区', '停车场B区', '停车场C区', '停车场D区'];
  
  for (let i = 1; i <= 20; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const exceptionType = exceptionTypes[Math.floor(Math.random() * exceptionTypes.length)];
    const parkingLot = parkingLots[Math.floor(Math.random() * parkingLots.length)];
    
    // 根据筛选条件过滤数据
    const statusText = status === 'pending' ? '待处理' : status === 'processing' ? '处理中' : '已处理';
    if (params.status > 0) {
      const filterStatus = params.status === 1 ? '待处理' : '已处理';
      if (statusText !== filterStatus) {
        continue;
      }
    }
    
    if (params.berthNumber && !`B${String(i).padStart(3, '0')}`.includes(params.berthNumber)) {
      continue;
    }
    
    records.push({
      id: i,
      berthNumber: `B${String(i).padStart(3, '0')}`,
      parkingLot,
      exceptionType,
      status,
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString(),
      processTime: status === 'completed' ? new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString() : '',
      processor: status === 'completed' ? ['张三', '李四', '王五'][Math.floor(Math.random() * 3)] : '',
      remark: status === 'completed' ? '已修复设备故障' : ''
    });
  }
  
  return { records };
};

// 页面挂载时获取数据
onMounted(() => {
  if (paging.value) {
    paging.value.reload();
  }
});
</script>

<style scoped lang="scss">
.abnormal-parking-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.filter-section {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .filter-item {
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
  }
}

// 列表卡片样式
.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .card-header {
    padding: 24rpx 30rpx 16rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      
      .number {
        color: #1890ff;
      }
    }
    
    .status-badge {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;
      
      &.status-pending {
        background: #fff2e8;
        color: #fa8c16;
      }
      
      &.status-processing {
        background: #e6f7ff;
        color: #1890ff;
      }
      
      &.status-completed {
        background: #f6ffed;
        color: #52c41a;
      }
    }
  }
  
  .card-content-box {
    padding: 20rpx 30rpx;
    
    .content {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }
        
        .value {
          font-size: 26rpx;
          color: #333;
          text-align: right;
          
          &.exception-type {
            font-weight: bold;
            
            &.type-offline {
              color: #ff4d4f;
            }
            
            &.type-low-battery {
              color: #fa8c16;
            }
            
            &.type-image-error {
              color: #722ed1;
            }
            
            &.type-time-error {
              color: #1890ff;
            }
            
            &.type-damage {
              color: #f5222d;
            }
          }
        }
      }
    }
    
    .card-footer {
      margin-top: 24rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f5f5f5;
      
      .operate {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;
        
        .custom-style {
          border-radius: 8rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}

// 弹窗样式
.process-modal,
.detail-modal {
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;
  
  .modal-header {
    padding: 30rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-content {
    padding: 30rpx;
    max-height: 600rpx;
    overflow-y: auto;
    
    .form-item,
    .detail-item {
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .form-label,
      .detail-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: block;
      }
      
      .detail-value {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .image-upload {
      .image-list {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        
        .image-item {
          position: relative;
          width: 120rpx;
          height: 120rpx;
          
          .uploaded-image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }
          
          .delete-icon {
            position: absolute;
            top: -8rpx;
            right: -8rpx;
            color: #ff4d4f;
            background: white;
            border-radius: 50%;
          }
        }
        
        .upload-btn {
          width: 120rpx;
          height: 120rpx;
          border: 2rpx dashed #d9d9d9;
          border-radius: 8rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #999;
          
          .upload-text {
            font-size: 20rpx;
            margin-top: 8rpx;
          }
        }
      }
    }
  }
  
  .modal-footer {
    padding: 30rpx;
    border-top: 1px solid #f5f5f5;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
  }
}
</style>